<template>
  <SectionContainer class="u-p20">
    <!-- 标题 -->
    <SectionTitle>其他账户管理</SectionTitle>

    <!-- 筛选 start -->
    <el-form
      class="m-filter"
      inline
    >
      <el-form-item>
        <el-select
          filterable
          size="small"
          placeholder="请选择账户"
          v-model="filter.account"
        >
          <el-option
            v-for="(item, index) in accountOptions"
            :key="index"
            :value="item.name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          filterable
          size="small"
          placeholder="请选择角色"
          v-model="filter.roleId"
        >
          <el-option
            v-for="(item, index) in roleOptions"
            :key="index"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          filterable
          size="small"
          placeholder="请选择账户状态"
          v-model="filter.status"
        >
          <el-option
            label="全部状态"
            :value="0"
          >
          </el-option>
          <el-option
            label="启用"
            :value="2"
          >
          </el-option>
          <el-option
            label="停用"
            :value="1"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          @click="search"
        >查询</el-button>
      </el-form-item>
    </el-form>
    <!-- 筛选 end -->

    <!-- 表格 start -->
    <TableFull
      :data="tableData"
      :total="tableTotal"
      :current-page="page.pageNo"
      @current-change="currentChange"
      @size-change="sizeChange"
    >
      <el-form
        class="m-filter"
        inline
        slot="handle"
      >
        <el-form-item>
          <el-button
            size="small"
            @click="openAccountDialog('create')"
          >
            新增
          </el-button>
        </el-form-item>
      </el-form>
      <template slot="column">
        <el-table-column
          :resizable="false"
          align="center"
          width="130"
          label="操作"
        >
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              placement="top"
              content="编辑"
            >
              <i
                class="u-table-handle iconfont iconfont-5"
                @click="openAccountDialog('edit', scope.row.userId)"
              ></i>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              placement="top"
              content="查看"
            >
              <i
                class="u-table-handle iconfont iconfont-6"
                @click="openAccountDialog('detail', scope.row.userId)"
              ></i>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              placement="top"
              content="重置密码"
            >
              <i
                class="u-table-handle iconfont iconfont-11"
                @click="handleResetPassword(scope.row.userId)"
              ></i>
            </el-tooltip>
            <el-tooltip
              v-if="scope.row.status === 1"
              effect="dark"
              placement="top"
              content="删除账户"
            >
              <i
                class="u-table-handle el-icon-circle-close"
                @click="openDeleteAccount([scope.row.userId])"
              ></i>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          :resizable="false"
          align="center"
          v-for="(item, index) in tableColumn"
          :key="index"
          :prop="item.prop"
          :sortable="item.sortable"
          :width="item.width"
          :label="item.label"
        >
          <template slot-scope="scope">
            <!-- 是否启用 -->
            <template v-if="item.prop === 'switch'">
              <el-switch
                v-if="[1, 2].includes(scope.row.status)"
                @change="openStatus([scope.row.userId], scope.row.status === 1 ? 2 : 1)"
                :value="scope.row.status"
                :active-value="2"
                :inactive-value="1"
              ></el-switch>
            </template>
            <!-- 其他 -->
            <template v-else>{{scope.row[item.prop]}}</template>
          </template>
        </el-table-column>
      </template>
    </TableFull>

    <!--启用-->
    <DialogConfirm
      :visible.sync="statusOpenVisible"
      :buttons="['启 用', '关 闭']"
      :button-primary="[0]"
      @confirm="confirmStatusOpen"
      content="是否要启用此账户？"
    ></DialogConfirm>

    <!--停用-->
    <DialogConfirm
      :visible.sync="statusCloseVisible"
      :buttons="['停 用', '关 闭']"
      :button-primary="[0]"
      @confirm="confirmStatusClose"
      content="是否停用此账户？"
      tip="停用后，账号不能正常登录系统，全部在投广告立刻停止投放！"
    ></DialogConfirm>

    <!-- 新增/编辑/查看账号 -->
    <Dialog
      :visible.sync="accountDialogVisible"
      :title="accountDialogTitle + '账号'"
      :width="520"
    >
      <el-form
        class="u-p20"
        label-width="100px"
        :model="accountData"
        :rules="accountRules"
        ref="accountForm"
      >
        <el-form-item
          prop="accountName"
          label="账户名称"
        >
          <el-input
            class="u-w320"
            placeholder="请输入账户名称"
            v-model="accountData.accountName"
            :disabled="accountDialogAction === 'detail'"
          ></el-input>
          <ShowWordLimit
            :value="accountData.accountName"
            :maxlength="20"
          ></ShowWordLimit>
        </el-form-item>
        <el-form-item
          prop="username"
          label="登录账号"
        >
          <el-input
            class="u-w320"
            placeholder="请填写邮箱账号，不可重复"
            v-model="accountData.username"
            :disabled="accountDialogAction === 'detail'"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="roleId"
          label="角色"
        >
          <el-select
            class="u-w320"
            placeholder="请选择角色"
            :disabled="accountDialogAction === 'detail'"
            v-model="accountData.roleId"
          >
            <el-option
              v-for="(item, index) in roleOptions.slice(1)"
              :key="index"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <template v-if="accountDialogAction === 'detail'">
          <el-form-item label="账号状态">{{accountData.accountStatus}}</el-form-item>
          <el-form-item label="最后操作人">{{accountData.updateBy}}</el-form-item>
          <el-form-item label="最后操作时间">{{accountData.updateDate}}</el-form-item>
        </template>
        <el-form-item
          label-width="0"
          class="u-mb0"
          align="center"
          v-if="['create', 'edit'].includes(accountDialogAction)"
        >
          <el-button
            type="primary"
            size="small"
            @click="handleSubmit"
          >确 定</el-button>
          <el-button
            size="small"
            @click="accountDialogVisible = false"
          >关 闭</el-button>
        </el-form-item>
      </el-form>
    </Dialog>

    <!--删除账户-->
    <DialogConfirm
      :visible.sync="deleteAccountVisible"
      :buttons="['确定删除', '取 消']"
      :button-primary="[0]"
      @confirm="confirmDeleteAccount"
      content="确定删除此账户？"
    ></DialogConfirm>

    <!--密码重置成功-->
    <Dialog
      :visible.sync="rePasswordDialogVisible"
      :width="350"
      title="密码重置成功"
    >
      <el-form
        align="center"
        class="u-p20"
      >
        <el-form-item class="u-mb0">
          密码：<span class="u-mr10">{{rePasswordDialogText}}</span>
          <el-button
            v-clipboard="rePasswordDialogText"
            type="text"
          >复制</el-button>
        </el-form-item>
        <el-form-item class="u-mb10">
          <Tip>请登录账户后自行修改密码</Tip>
        </el-form-item>
        <el-form-item class="u-mb0">
          <el-button
            type="primary"
            size="small"
            @click="rePasswordDialogVisible = false"
          >关闭</el-button>
        </el-form-item>
      </el-form>
    </Dialog>
  </SectionContainer>
</template>

<script>
import SectionTitle from "@/components/section-title";
import SectionContainer from "@/components/section-container";
import Tip from "@/components/tip";
import Dialog from "@/components/dialog";
import DialogConfirm from "@/components/dialog-confirm";
import TableFull from "@/components/table-full";
import ShowWordLimit from "@/components/show-word-limit";

import permissionMixin from "@/mixins/permission";
import { splitAccount, getStrLen } from "@/utils";

import {
  fetchAccountAdminRoleSelect,
  fetchAccountAdminAdd,
  fetchAccountAdminDetail,
  fetchAccountAdminList,
  fetchAccountAdminSelect,
  fetchAccountAdminUpdate,
  fetchAccountRestPwd,
  fetchAccountStatus,
  fetchAccountDelete
} from "@/api";

export default {
  mixins: [permissionMixin],
  components: {
    SectionTitle,
    SectionContainer,
    Tip,
    Dialog,
    DialogConfirm,
    TableFull,
    ShowWordLimit
  },
  data() {
    return {
      accountOptions: [],
      roleOptions: [],

      // 筛选
      filter: {
        account: "全部账户",
        status: 0,
        roleId: ""
      },

      // 分页
      page: {
        pageNo: 1,
        pageSize: 50
      },

      // 密码重置
      rePasswordDialogText: "DSP123456",
      rePasswordDialogVisible: false,

      // 删除账户
      deleteAccountVisible: false,
      deleteAccountIds: [],

      // 新增/编辑/查看账号
      accountDialogVisible: false,
      accountDialogTitle: "",
      accountDialogAction: "",
      accountData: {},
      accountRules: {
        accountName: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value || value.trim() === "") {
              callback(new Error("请输入账户名称"));
            } else if (getStrLen(value) > 20) {
              callback(new Error("账户名称不能超过20个字符"));
            } else {
              callback();
            }
          },
          trigger: ["change", "blur"]
        },
        username: {
          required: true,
          message: "请输入登录账号",
          trigger: ["change", "blur"]
        },
        roleId: {
          required: true,
          message: "请选择角色",
          trigger: ["change", "blur"]
        }
      },

      // 是否启用
      statusKeys: [],
      statusOpenVisible: false,
      statusCloseVisible: false,

      // 表格
      tableColumn: [
        {
          label: "账户名称",
          prop: "accountName"
        },
        {
          label: "登录账号",
          prop: "userName"
        },
        {
          label: "角色",
          prop: "roleName"
        },
        {
          label: "账户状态",
          prop: "accountStatus"
        },
        {
          label: "是否启用",
          prop: "switch"
        }
      ],
      tableData: [],
      tableTotal: 0
    };
  },
  methods: {
    // 删除账户
    handleDeleteAccount() {
      return fetchAccountDelete({
        query: {
          ids: this.deleteAccountIds.join()
        }
      });
    },
    // 删除账户/打开弹窗
    openDeleteAccount(ids) {
      this.deleteAccountIds = ids;
      this.deleteAccountVisible = true;
    },
    // 删除账户/确认删除
    confirmDeleteAccount(index) {
      if (index === 0) {
        this.handleDeleteAccount().then(() => {
          this.$message({
            message: "删除成功",
            duration: 1000
          });
          this.deleteAccountVisible = false;
          this.getTable();
        });
      } else {
        this.deleteAccountVisible = false;
      }
    },
    // 新增/编辑/查看账号
    openAccountDialog(action, userId) {
      this.accountDialogTitle = {
        create: "新增",
        edit: "编辑",
        detail: "查看"
      }[action];
      this.accountDialogAction = action;
      this.accountDialogVisible = true;
      if (["edit", "detail"].includes(action)) {
        this.fetchAccountAdminDetail(userId);
      } else {
        this.accountData = {};
      }
    },
    // 账户确定
    handleSubmit() {
      this.$refs.accountForm.validate(valid => {
        if (valid) {
          if (this.accountDialogAction === "create") {
            this.fetchAccountAdminAdd();
          } else if (this.accountDialogAction === "edit") {
            this.fetchAccountAdminUpdate();
          }
        } else {
          return false;
        }
      });
    },
    // 账户新增
    fetchAccountAdminAdd() {
      let { roleId, accountName, username } = this.accountData;
      fetchAccountAdminAdd({
        query: {
          roleId
        },
        body: {
          accountName,
          username,
          userType: 2
        }
      }).then(() => {
        this.$message.info("账户新增成功");
        this.accountDialogVisible = false;
        this.search();
      });
    },
    // 账户更新
    fetchAccountAdminUpdate() {
      let { roleId, accountName, username, userId } = this.accountData;
      fetchAccountAdminUpdate({
        query: {
          roleId
        },
        body: {
          accountName,
          username,
          id: userId,
          userType: 2
        }
      }).then(() => {
        this.$message.info("账户修改成功");
        this.accountDialogVisible = false;
        this.search();
      });
    },
    // 账户详情
    fetchAccountAdminDetail(userId) {
      fetchAccountAdminDetail({
        query: {
          userId
        }
      }).then(res => {
        this.accountData = res.data;
      });
    },
    // 管理员角色
    fetchAccountAdminRoleSelect() {
      fetchAccountAdminRoleSelect().then(res => {
        this.roleOptions = [
          {
            name: "全部角色",
            id: ""
          }
        ].concat(res.data.list || []);
        // 默认角色
        if (this.$route.query.roleId) {
          this.filter.roleId = Number(this.$route.query.roleId);
        }
      });
    },
    // 账户下拉
    fetchAccountAdminSelect() {
      fetchAccountAdminSelect().then(res => {
        this.accountOptions = [
          {
            name: "全部账户"
          }
        ].concat(res.data);
      });
    },
    // 获取表格数据
    getTable() {
      this.tableData = [];
      this.tableTotal = 0;
      fetchAccountAdminList({
        body: {
          ...this.page,
          status: this.filter.status,
          roleId: this.filter.roleId || Number(this.$route.query.roleId) || 0,
          account:
            this.filter.account === "全部账户"
              ? ""
              : splitAccount(this.filter.account).name
        }
      }).then(res => {
        this.tableData = res.data.dataList || [];
        this.tableTotal = res.data.dataListCount;
      });
    },
    search() {
      this.page.pageNo = 1;
      this.getTable();
    },
    // 是否启用
    openStatus(keys, status) {
      this.statusKeys = keys;
      if (status === 1) {
        this.statusCloseVisible = true;
      } else if (status === 2) {
        this.statusOpenVisible = true;
      }
    },
    // 是否启用/切换状态
    changeStatus(keys, value) {
      return fetchAccountStatus({
        query: {
          ids: keys.join(),
          status: value
        }
      }).then(() => {
        this.$message({
          message: "操作成功",
          duration: 1000
        });
      });
    },
    // 是否启用/确认启用
    confirmStatusOpen(index) {
      if (index === 0) {
        this.changeStatus(this.statusKeys, 2).then(() => {
          this.statusOpenVisible = false;
          this.getTable();
        });
      } else {
        this.statusOpenVisible = false;
      }
    },
    // 是否启用/确认停用
    confirmStatusClose(index) {
      if (index === 0) {
        this.changeStatus(this.statusKeys, 1).then(() => {
          this.statusCloseVisible = false;
          this.getTable();
        });
      } else {
        this.statusCloseVisible = false;
      }
    },
    // 重置密码
    handleResetPassword(userId) {
      fetchAccountRestPwd({
        query: {
          userId
        }
      }).then(() => {
        this.rePasswordDialogVisible = true;
      });
    },
    // 分页
    currentChange(val) {
      this.page.pageNo = val;
      this.getTable();
    },
    sizeChange(val) {
      this.page.pageSize = val;
      this.getTable();
    }
  },
  created() {
    this.fetchAccountAdminSelect();
    this.fetchAccountAdminRoleSelect();
    this.getTable();
  }
};
</script>
